<template>
  <view class="container bg-white w-100 h-100">
    <!-- #ifdef MP-WEIXIN -->
    <uv-navbar
      :fixed="false"
      :title="title"
      left-arrow
      @leftClick="$onClickLeft"
    />
    <!-- #endif -->

    <!--协议弹出框-->
    <uv-popup mode="bottom" :closeable="true" ref="refPopup">
      <view
        class="pre-line font-size-sm text-color-assist"
        style="margin-bottom: 200rpx; padding: 30rpx"
        >{{ agreement }}</view
      >
    </uv-popup>

    <!--轻提示-->
    <uv-toast ref="uToast"></uv-toast>

    <view style="padding-bottom: 220rpx">
      <view class="balance-info d-flex justify-content-between">
        <view
          class="flex-fill d-flex flex-column align-items-between justify-content-between"
        >
          <view class="font-size-sm text-color-base">{{
            currentLanguageTexts.accountBalance
          }}</view>
          <view class="font-size-extra-lg text-color-base font-weight-bold">{{
            member.nowMoney
          }}</view>
          <view class="font-size-sm text-color-primary" @click="goBill">{{
            currentLanguageTexts.transactionRecord
          }}</view>
        </view>
        <image
          src="/static/images/balance.png"
          style="height: 194rpx"
          mode="aspectFit"
        ></image>
      </view>

      <view
        class="font-size-lg text-color-base font-weight-bold"
        style="margin-bottom: 20rpx"
        >{{ currentLanguageTexts.storedValueAmount }}</view
      >

      <view class="d-flex flex-wrap justify-content-between amounts">
        <view
          class="d-flex align-items-center just-content-center amount"
          :class="{
            'bg-primary text-color-white': item.selected,
            'bg-base text-color-base': !item.selected,
          }"
          v-for="(item, index) in amounts"
          :key="index"
          @tap="handleSelected(index)"
        >
          <view class="font-size-extra-lg font-weight-bold">{{
            parseInt(item.value)
          }}</view>
          <view class="font-size-sm font-weight-light">{{
            currentLanguageTexts.yuan
          }}</view>
        </view>
      </view>

      <view
        class="font-size-lg text-color-base font-weight-bold mt-5"
        style="margin-bottom: 20rpx"
        >{{ currentLanguageTexts.payWay }}</view
      >
      <list-cell last>
        <view
          class="d-flex align-items-center justify-content-between w-100"
          @click="setPayType('weixin')"
        >
          <view
            class="iconfont iconwxpay line-height-100 payment-icon"
            style="color: #7eb73a"
          ></view>
          <view class="flex-fill">{{ currentLanguageTexts.wxPay }}</view>
          <view
            class="iconfont line-height-100 checkbox checked iconradio-button-on"
            v-if="payType == 'weixin'"
          >
          </view>
          <view
            class="iconfont line-height-100 checkbox iconradio-button-off"
            v-else
          ></view>
        </view>
      </list-cell>
      <!-- #ifdef H5 -->
      <!-- 		<list-cell>
				<view class="d-flex align-items-center justify-content-between w-100" @click="setPayType('alipay')">
					<view class="iconfont-yshop icon-alipay line-height-100 payment-icon" style="color:#07b4fd" ></view>
					<view class="flex-fill">支付宝</view>
					<view class="iconfont line-height-100 checkbox checked iconradio-button-on" v-if="payType == 'alipay'" ></view>
					<view class="iconfont line-height-100 checkbox iconradio-button-off" v-else ></view>     
				</view>
			</list-cell> -->
      <!-- #endif -->

      <!-- bottom box begin -->
      <view
        class="bottom-box position-fixed fixed-bottom w-100 d-flex flex-column bg-white"
      >
        <view
          class="protocol font-size-sm d-flex justify-content-start align-items-center"
        >
          <view
            class="iconfont line-height-100"
            @tap="agree = !agree"
            :class="{
              'iconradio-button-on text-color-primary': agree,
              'iconradio-button-off text-color-base': !agree,
            }"
          ></view>
          <view class="text-color-base">{{
            currentLanguageTexts.readAndFollow
          }}</view>
          <view class="text-color-primary" @click="popup"
            >《{{ currentLanguageTexts.storedValueAgreementLabel }}》</view
          >
        </view>
        <uv-button
          type="primary"
          class="b"
          @click="buy"
          :custom-style="{
            borderRadius: '40rpx',
            fontWeight: 'bold',
            color: '#333',
          }"
          >{{ currentLanguageTexts.buy }}</uv-button
        >
      </view>
      <!-- bottom box end -->
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useMainStore } from '@/store/store';
import { storeToRefs } from 'pinia';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { isWeixin } from '@/utils/util';
import { balanceGetMoneyList, balanceRecharge } from '@/api/user';
import { payUnify, getWechatConfig } from '@/api/order';
// #ifdef H5
import * as jweixin from 'weixin-js-sdk';
// #endif
const main = useMainStore();
const { isLogin, member, currentLanguageTexts } = storeToRefs(main);
const title = ref('充值');
const agree = ref(false);
const amounts = ref([]);
const show = ref(false);
const agreement = currentLanguageTexts.value.storedValueAgreement;
const refPopup = ref();
const payType = ref('weixin');

onLoad(() => {
  getManeyList();
});

const getManeyList = async () => {
  let data = await balanceGetMoneyList();
  if (data) {
    amounts.value = data;
  }
};

const handleSelected = (index) => {
  amounts.value.forEach((item) => (item.selected = false));
  amounts.value[index].selected = true;
};

// 更改支付方式
const setPayType = (paytype) => {
  payType.value = paytype;
};

const buy = async () => {
  if (agree.value == false) {
    uToast.value.show({
      messsage: currentLanguageTexts.value.agreeStoredAgreement,
      type: 'success',
    });
    return;
  }
  let selected = false;
  let recharge = 0;
  amounts.value.forEach((item) => {
    if (item.selected == true) {
      selected = true;
      recharge = item;
    }
  });
  if (selected == false) {
    uToast.value.show({
      message: currentLanguageTexts.value.rechargeAmountPlaceholder,
      type: 'error',
    });
    return;
  }

  let resData = await balanceRecharge({
    rechargeId: recharge.id,
  });
  if (!resData) {
    return;
  }
  let order = { orderId: resData };

  if (payType.value == 'weixin') {
    // 微信支付
    weixinPay(order);
  } else if (payType.value == 'alipay') {
    // 余额支付
    aliPay(order);
  }
};
const weixinPay = async (order) => {
  let from = 'routine';
  // #ifdef H5
  from = 'h5';
  if (isWeixin()) {
    from = 'wechat';
  }

  // #endif
  //let that = this;
  let data = await payUnify({
    uni: order.orderId,
    from: from,
    paytype: 'weixin',
  });
  if (!data) {
    return;
  }
  if (data.trade_type == 'MWEB') {
    // #ifdef H5
    // 微信外的H5
    location.href = data.data;
    // #endif
  } else if (data.trade_type == 'JSAPI') {
    // #ifdef MP-WEIXIN
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: data.data.timeStamp,
      nonceStr: data.data.nonceStr,
      package: data.data.package,
      signType: 'MD5',
      paySign: data.data.paySign,
      success: function (res) {
        uni.switchTab({
          url: '/pages/mine/mine',
        });
      },
      fail: function (err) {
        console.log('fail:' + JSON.stringify(err));
      },
    });
    // #endif
  } else if (data.trade_type == 'W-JSAPI') {
    //公众号支付
    let config = await getWechatConfig();
    console.log('config:', config);
    if (config) {
      jweixin.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: config.appId, // 必填，公众号的唯一标识
        timestamp: config.timestamp, // 必填，生成签名的时间戳
        nonceStr: config.nonceStr, // 必填，生成签名的随机串
        signature: config.signature, // 必填，签名
        jsApiList: ['chooseWXPay'],
      });
      jweixin.ready(function () {
        jweixin.chooseWXPay({
          timestamp: data.data.timeStamp,
          nonceStr: data.data.nonceStr,
          package: data.data.package,
          signType: 'MD5',
          paySign: data.data.paySign,
          success: function (res) {
            uni.removeStorageSync('cart');
            uni.switchTab({
              url: '/pages/mine/mine',
            });
          },
          fail: function (err) {
            console.log(res);
          },
        });
      });
      jweixin.error(function (res) {
        console.log(res);
      });
    } else {
      // console.log(res)
    }
  }
};

const aliPay = async (order) => {
  // #ifdef H5
  //let that = this;
  if (isWeixin()) {
    uni.showToast({
      title: '请普通浏览器打开进行支付宝支付~',
      icon: 'none',
    });
    return;
  }
  let data = await payUnify({
    uni: order.orderId,
    from: 'h5',
    paytype: 'alipay',
  });

  // 支付宝支付，这里只要提交表单
  let form = data.data;
  const div = document.createElement('formdiv');
  div.innerHTML = form;
  document.body.appendChild(div);
  document.forms[0].submit();

  // #endif
};

// 弹出层
const popup = () => {
  refPopup.value.open();
};
const goBill = () => {
  uni.navigateTo({
    url: '/pages/components/pages/balance/bill?cate=0&type=2',
  });
};
</script>

<style lang="scss" scoped>
.container {
  padding: 0 40rpx;
}

.balance-info {
  padding: 50rpx 10rpx;

  view {
    height: calc(366 / 638 * 340);
    padding: 10rpx 0;
  }
  image {
    width: 340rpx;
  }
}

.amounts {
  margin-bottom: 40rpx;
  .amount {
    width: calc(96% / 3);
    padding: 50rpx 0;
    margin-bottom: 20rpx;
    border-radius: 8rpx;
  }
}

.bottom-box {
  padding: 0 40rpx 30rpx;
  box-shadow: 0 0 20rpx rgba(6, 6, 6, 0.1);

  .protocol {
    padding: 36rpx 0;
    height: 100rpx;
    view {
      margin-right: 10rpx;
    }
  }

  button {
    height: 70rpx;
    line-height: 70rpx;
    border-radius: 50rem !important;
    margin-bottom: 30rpx;
  }
}
</style>
